<template>
  <div class="form-service-provider">
    <!-- 添加按钮 S -->
    <el-button
      class="add-subform-btn"
      icon="el-icon-plus"
      @click="createServiceProviderFields"
    >
      {{$t('common.base.addModule', {module:''})}}
    </el-button>
    <!-- 添加按钮 E -->

    <!-- 服务商表单表格 S -->
    <el-table
      v-table-style
      :data="serviceProviderFieldsValues"
      header-row-class-name="common-list-table-header__v2"
      border
    >
      <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        :min-width="column.minWidth || '108px'"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{
            $formatFormField(column, scope.row)
          }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('common.base.operation')" width="60">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="deleteProviderFieldValue(scope.$index)"
          >
            {{$t('common.base.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 服务商表单表格 E -->

    <!-- 添加子表单数据弹窗 S -->
    <base-modal
      :title="title"
      :show.sync="visible"
      width="600px"
      
    >
      <div class="service-form">
        <form-builder
          v-if="visible"
          ref="form"
          :fields="subFields"
          :value="form"
          @update="update"
        >
          <!-- 服务商名称 S -->
          <template slot="providerName" slot-scope="{ field }">
            <form-item :label="field.displayName">
              <biz-form-remote-select
                :field="field"
                v-model="selectedProvider"
                :remote-method="searchProvider"
                @input="updateProvider"
                :placeholder="$t('common.placeholder.selectSomething', {0:$t('common.form.type.serviceProviders')})"
              >
                <div
                  class="service-template-option"
                  slot="option"
                  slot-scope="{ option }"
                >
                  <h3>{{ option.name }}</h3>
                  <div>
                    <label>{{$t('common.form.preview.subServiceProvider.label1')}}</label>
                    <span>{{ option.providerCode }}</span>
                  </div>
                </div>
              </biz-form-remote-select>
            </form-item>
          </template>
          <!-- 服务商名称 E -->
        </form-builder>
      </div>

      <div slot="footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="onSubmit">{{$t('common.base.confirm')}}</el-button>
      </div>
    </base-modal>
    <!-- 添加子表单数据弹窗 E -->
  </div>
</template>

<script>
import _ from 'lodash';
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
/* util */
import * as FormUtil from '@src/component/form/util';
/** api */
import { getProviderData } from '@src/api/FieldApi.ts';

import { SUBFORM_FIELDS_ADD_LENGTH_MAX } from '@src/component/form/config';

export default {
  name: 'form-service-provider',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      visible: false,
      serviceProviderFieldsValues: this.value || [],
      form: {},
      selectedProvider: [], // 当前选中的服务商
    };
  },
  computed: {
    // 标题
    title() {
      return this.$t('common.base.addModule', {module:this.field?.displayName || ''});
    },
    // 表单表头
    columns() {
      let columns = this.field?.subFormFieldList ? [...this.field?.subFormFieldList] : [];

      columns.map(field => {
        field.label = field.displayName;
        field.field = field.fieldName;
      });

      return columns;
    },
    // 服务商表单数据
    subFields() {
      let fields = this.field?.subFormFieldList ? [...this.field?.subFormFieldList] : [];

      fields.forEach(item => {
        if (item.fieldName == 'providerName') {
          item.isNull = 0
          item.formType = 'select'
        } else {
          item.isNull = 1;
        }
      });

      return fields;
    },
  },
  watch: {
    // 编辑工单 || 编辑产品数据回显
    value(newValue) {
      this.serviceProviderFieldsValues = newValue || [];
    },
  },
  methods: {
    // 重置数据
    resetForm() {
      this.selectedProvider = [];
      this.form = FormUtil.initialize(this.subFields, {});
    },
    // 点击添加
    createServiceProviderFields() {
      if (this.serviceProviderFieldsValues.length >= SUBFORM_FIELDS_ADD_LENGTH_MAX)
        return this.$message.warning(this.$t('common.form.tip.alowAddDataCount', {data1:SUBFORM_FIELDS_ADD_LENGTH_MAX}));
      
      this.visible = true;
      this.resetForm();
    },

    // 删除表单
    deleteProviderFieldValue(index) {
      this.serviceProviderFieldsValues.splice(index, 1);
      this.inputForValue(this.serviceProviderFieldsValues);
    },

    /**
     * @description 搜索
     */
    async searchProvider(params = {}) {
      return this.fetchProviderList(params);
    },
    async fetchProviderList(params = {}) {
      try {
        let result = {};
        params.depth = 1 // 一级服务商
        let res = await getProviderData(params);
        if (!res.success) return;

        result = res.result;

        result.list = result.list.map(provider => {
          return Object.freeze({
            ...provider,
            label: provider.name,
            value: provider.tenantProviderId
          });
        });
        return result;
      } catch (error) {
        console.warn('task-edit-form: fetchProviderList -> error', error);
      }
    },

    getAddress(fieldVal) {
      return fieldVal?.province + fieldVal?.city + fieldVal?.dist + fieldVal?.address || '';
    },
    getCascader (fieldVal) {
      return Array.isArray(fieldVal) ? fieldVal.join(',') : fieldVal;
    },
    getUser(fieldVal) {
      return Array.isArray(fieldVal) ? fieldVal.map(v => v.displayName).join(',') : fieldVal?.displayName || '';
    },
    /**
     * @description 选择服务商
     */
    updateProvider(value) {
      try {
        let newValue = value[0];
        if(!newValue) return;

        this.subFields.map(field => {
          let fieldName = field.fieldName;
          let formType = field.setting.originalFormType;

          // 服务商子表单目前都是以input展示，所以有些数据需要特殊处理
          let fieldVal = newValue[fieldName] || (newValue.formVOList ? newValue.formVOList[fieldName] : '')

          if (formType === 'address') {
            this.form[fieldName] = fieldVal?.all || this.getAddress(fieldVal)
          } else if (formType === 'cascader') {
            this.form[fieldName] = this.getCascader(fieldVal)
          } else if (formType === 'user') {
            this.form[fieldName] = this.getUser(fieldVal);
          } else {
            this.form[fieldName] = fieldVal;
          }
        });

        this.form['providerName'] = newValue.name;
        this.form['serviceProviderId'] = newValue.tenantProviderId; // 服务商id
        this.form['providerType'] = newValue.type; // 服务商类型
      } catch(error) {
        console.error(error)
      }
    },

    // 更新表格数据
    updateTableData() {
      this.serviceProviderFieldsValues.push(this.form);
      this.inputForValue(this.serviceProviderFieldsValues);
      this.visible = false;
      this.form = {};
    },
    /**
     * @description: 提交表单
     */
    async onSubmit() {
      // 校验表单必填项
      const validateRes = await this.$refs.form.validate(false);
      if (!validateRes) return;

      // 校验服务商是否添加重复
      let isExit = (this.serviceProviderFieldsValues || []).some(
        v => v?.serviceProviderId == this.form.serviceProviderId
      );
      if (isExit) return this.$message.warning(this.$t('common.base.tip.notAddRepeatedlyModule', {module:this.$t('common.form.type.serviceProviders')}));

      this.updateTableData();
    },

    // 更新表单数据
    update({ field, newValue, oldValue }) {
      let { fieldName } = field;
      this.$set(this.form, fieldName, newValue);
    }
  }
};
</script>
<style lang="scss" scoped>
.form-service-provider {
  .add-subform-btn {
    color: $color-primary;
    border-color: $color-primary-light-2;
    background-color: $color-primary-light-1;
    margin-bottom: 12px;
    &:hover {
      background: $color-primary-light-6;
      border-color: $color-primary-light-6;
      color: #fff;
    }
  }
}
.service-form {
  .service-template-option {
    font-size: 12px;
    line-height: 14px;
    padding: 10px 0;
  }
}
</style>